<?php

namespace IDock\Insurance\TPIC\Response;

use IDock\Http\Response;
use Throwable;

class AllTPICResponse extends Response
{

    protected $status = '';

    public $contents;

    public function resolve(): Response
    {
        $body = $this->getBody();

        $this->contents = $body;

        if ($this->printer) {
            $this->printer = new $this->printer;
        }
        try {
            simplexml_load_string($body);
        } catch (Throwable $exception) {
            $this->setError('返回数据格式错误');
            return $this;
        }

        if ($body) {
            $xml = simplexml_load_string($body);
            $body = $this->objectToArray($xml);
            $status = $body['head']['status'] ?? '';
            $message = $body['head']['errMsg'] ?? '';
            $this->setBody($body);
            if ($status != 'S') {
                $this->setError(($status ?: '') . ":" . $message);
                return $this;
            }
        }

        return $this;
    }

    public function objectToArray($object)
    {
        if (count($object) == 0) return trim((string)$object);
        $result = array();
        $object = is_object($object) ? get_object_vars($object) : $object;
        foreach ($object as $key => $val) {
            $val = (is_object($val) || is_array($val)) ? $this->objectToArray($val) : $val;
            $result[$key] = $val;
        }
        return $result;
    }

    /**
     * 格式化数组为多维
     * @param array $arr
     * @return array
     */
    public function formatArray(array $arr)
    {
        if (empty($arr)) return $arr;
        if (!isset($arr[0])) {
            $tmp = $arr;
            unset($arr);
            $arr[] = $tmp;
        }
        return $arr;
    }

}
